package nix.mall.order.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.pojo.User;
import nix.mall.sso.service.UserService;
import nix.mall.utils.CookieUtils;

/**
 * 用户登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Value("${TOKEN_KEY}")
	private String TOKEN_KEY;
	
	@Value("${SSO_URL}")
	private String SSO_URL;
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		/*执行handler之前执行此方法
		返回true放行；返回false拦截*/
		// 从Cookie中取tocken信息
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		// 取不到token，跳转sso登陆页，当前url作为参数传递，sso登陆成功后跳转回请求页面
		if (StringUtils.isBlank(token)) {
			// 取当前请求的url
			String requestURL = request.getRequestURL().toString();
			// 跳转
			response.sendRedirect(SSO_URL + "/sso/login.html?url=" + requestURL);
			// 拦截
			return false;
		}
		// 取到token，调用sso服务判断用户是否登陆
		NixMallResult result = userService.getUserByToken(token);
		// 如果未登录，跳转sso登陆页，当前url作为参数传递，sso登陆成功后跳转回请求页面
		if (result.getStatus() != 200) {
			// 取当前请求的url
			String requestURL = request.getRequestURL().toString();
			// 跳转
			response.sendRedirect(SSO_URL + "/sso/login.html?url=" + requestURL);
			// 拦截
			return false;
		}
		// 如果已登录，用户信息放入request，放行
		User user = (User) result.getData();
		request.setAttribute("user", user);
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
		/*handler执行之后，modelAndView返回之前，执行此方法*/
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		/*modelAndView返回之后，执行此方法*/
	}
}
